#!/usr/bin/env python3
"""
日志清理脚本
定期清理过期的日志文件
"""

import os
import sys
import time
from pathlib import Path
from datetime import datetime, timedelta

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

def cleanup_logs(log_dir: str = "logs", max_age_days: int = 7, max_size_mb: int = 100):
    """
    清理日志文件
    
    Args:
        log_dir: 日志目录
        max_age_days: 最大保留天数
        max_size_mb: 单个文件最大大小(MB)
    """
    log_path = Path(log_dir)
    
    if not log_path.exists():
        print(f"日志目录不存在: {log_path}")
        return
    
    print(f"开始清理日志目录: {log_path}")
    
    # 计算过期时间
    cutoff_time = datetime.now() - timedelta(days=max_age_days)
    cutoff_timestamp = cutoff_time.timestamp()
    
    cleaned_files = 0
    cleaned_size = 0
    
    # 遍历日志文件
    for log_file in log_path.glob("*.log*"):
        try:
            # 获取文件信息
            stat = log_file.stat()
            file_size_mb = stat.st_size / (1024 * 1024)
            file_mtime = stat.st_mtime
            
            # 检查是否需要删除
            should_delete = False
            reason = ""
            
            # 检查文件年龄
            if file_mtime < cutoff_timestamp:
                should_delete = True
                reason = f"文件过期 (>{max_age_days}天)"
            
            # 检查文件大小
            elif file_size_mb > max_size_mb:
                should_delete = True
                reason = f"文件过大 (>{max_size_mb}MB)"
            
            if should_delete:
                print(f"删除文件: {log_file.name} - {reason}")
                log_file.unlink()
                cleaned_files += 1
                cleaned_size += file_size_mb
            else:
                print(f"保留文件: {log_file.name} ({file_size_mb:.2f}MB)")
                
        except Exception as e:
            print(f"处理文件 {log_file} 时出错: {e}")
    
    print(f"清理完成: 删除了 {cleaned_files} 个文件，释放了 {cleaned_size:.2f}MB 空间")

def main():
    """主函数"""
    print(f"日志清理脚本启动 - {datetime.now()}")
    
    # 清理应用日志
    cleanup_logs("logs", max_age_days=3, max_size_mb=50)
    
    # 清理Docker日志（如果存在）
    docker_log_dir = "/var/lib/docker/containers"
    if Path(docker_log_dir).exists():
        print("清理Docker容器日志...")
        try:
            # 这里只是示例，实际生产环境中需要更谨慎
            os.system("find /var/lib/docker/containers -name '*.log' -mtime +7 -delete 2>/dev/null || true")
        except Exception as e:
            print(f"清理Docker日志时出错: {e}")
    
    print("日志清理完成")

if __name__ == "__main__":
    main()
